package com.example.aslongastoday.ui.backlog;

import static android.content.Context.MODE_PRIVATE;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.aslongastoday.R;
import com.example.aslongastoday.adapter.ViewBackLogGroupAdapter;
import com.example.aslongastoday.bean.BeanFactory;
import com.example.aslongastoday.db.dao.BackLogGroupDao;
import com.example.aslongastoday.domain.BackLog;
import com.example.aslongastoday.domain.BackLogGroup;
import com.example.aslongastoday.util.CloudUtil;
import com.example.aslongastoday.util.ColorChangeUtil;
import com.example.aslongastoday.util.TimeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class BackLogFragment extends Fragment{

    private static final String PREFS_NAME = "MyPrefsFile";
    private static final String KEY_FIRST_RUN = "firstRun";
    private static final String ARG_COLUMN_COUNT = "column-count";
    private EditBacklogFragment editBacklogFragment;
    private FragmentManager fragmentManager; //声明一个管理fragment的fragmentManager

    private FragmentTransaction fragmentTransaction; //声明一个fragmentTransaction
    private BackLogGroupDao dao; //用于处理待办组数据的Dao类
    private List<BackLogGroup> list = new ArrayList<>();

    private View view; //待办模块的主fragment对应的视图类
    private RecyclerView recyclerView; //循环列表的视图类
    private View backlogListView; //待办组列表的视图类

    private ViewBackLogGroupAdapter viewBackLogGroupAdapter;//待办主视图的适配器
    private Bundle bundle;
    private String type;
    private RecycleFragment recycleFragment;
    private ThemesChangeFragment themesChangeFragment;

    public BackLogFragment() {
    }

    public void onItemClick(int position) {
        editBacklogFragment = new EditBacklogFragment();
        //Bundle bundle = new Bundle();
        //bundle.putInt("position", position);
        //fragment.setArguments(bundle);
        fragmentManager = getActivity().getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container, editBacklogFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    public static BackLogFragment newInstance(int columnCount) {
        BackLogFragment fragment = new BackLogFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //mRecyclerView = view.findViewById(R.id.it_addBacklogGroup);
    }


    //加载菜单文件
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.backlog_main_menu, menu);
    }

    //实现菜单项事件
    @Override
    public boolean onContextItemSelected(MenuItem item) {


        switch (item.getItemId()) {
            //新建待办组
            case R.id.it_addBacklogGroup:
                //新建一个实例化对象
                editBacklogFragment = new EditBacklogFragment();
                //数据打包
                bundle = new Bundle();
                type = "add_backlog_group";
                bundle.putString("type", type);
                editBacklogFragment.setArguments(bundle);
                // 跳转到EditBacklogFragment
                fragmentManager = getActivity().getSupportFragmentManager();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.container, editBacklogFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                return true;
            case R.id.it_recycle:
                // 打开回收站
                //新建一个实例化对象
                recycleFragment = new RecycleFragment(viewBackLogGroupAdapter);
                // 跳转到EditBacklogFragment
                fragmentManager = getActivity().getSupportFragmentManager();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.container, recycleFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();

                return true;
            case R.id.it_themes:
                // 打开主题切换, 优先实现深浅色切换
/*                themesChangeFragment = new ThemesChangeFragment();
                fragmentManager = getActivity().getSupportFragmentManager();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.container, themesChangeFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();*/
//                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                ColorChangeUtil.changeColor();
                return true;
            case R.id.it_localToCloud:
                //本地数据上传到云端
                if (CloudUtil.getLoginUserInfo().equals("--")){
                    Toast.makeText(view.getContext(), "请先登录后再使用该功能！", Toast.LENGTH_SHORT).show();
                    return true;
                }
                List<BackLogGroup> backLogGroupList = dao.queryAll();
                try {
                    CloudUtil.PushBackLog(backLogGroupList);
                    Toast.makeText(view.getContext(), "成功上传到云端！", Toast.LENGTH_SHORT).show();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return true;
            case R.id.it_cloudToLocal:
                //云端数据同步到本地
                if (CloudUtil.getLoginUserInfo().equals("--")){
                    Toast.makeText(view.getContext(), "请先登录后再使用该功能！", Toast.LENGTH_SHORT).show();
                    return true;
                }
                try {
                    List<BackLogGroup> groupList = CloudUtil.PullBackLog();
                    deleteData();
                    dao.insert(groupList);
                    List<BackLogGroup> all = dao.queryUnfinishedAll();
                    viewBackLogGroupAdapter.setBackLogGroupList(all);
                    viewBackLogGroupAdapter.notifyDataSetChanged();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }

                return true;


            default:
                return super.onContextItemSelected(item);
        }

    }

    public void lazyDelete(){
        List<BackLogGroup> backLogGroupList = dao.queryAll();
        for (BackLogGroup backLogGroup : backLogGroupList) {
            List<BackLog> backLogList = backLogGroup.getBackLogList();
            for (int i = backLogList.size() - 1; i >= 0; i--) {
                if (backLogList.get(i).getStatus()==2) {
                    backLogList.remove(i);
                }
            }
        }
        deleteData();
        dao.insert(backLogGroupList);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_backlog, container, false);
        dao = BackLogGroupDao.getInstance(view.getContext());

        //当软件第一次被使用的时候，执行以下代码
        if (!onAppInit()) {
            //初始化数据库时，懒加载删除永久删除的待办项
            lazyDelete();
        }
        list = dao.queryUnfinishedAll();
        backlogListView = view.findViewById(R.id.backlog_list_rv);
        // Set the adapter 如果是右边类的实例
        if (backlogListView instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) backlogListView;
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
            viewBackLogGroupAdapter = new ViewBackLogGroupAdapter(list, context, this);

            //放入享元的Map
            BeanFactory.addBean("viewBackLogGroupAdapter", viewBackLogGroupAdapter);

            recyclerView.setAdapter(viewBackLogGroupAdapter);
        }

        /* 待办主页的功能按键监听*/
        initButton();
        return view;
    }

    /**
     * 待办主页的功能按键监听
     */
    public void initButton() {
        //注册iv_list的上下文菜单
        ImageView iv_list = view.findViewById(R.id.iv_list);
        registerForContextMenu(iv_list);
        iv_list.setOnClickListener(v -> v.showContextMenu());
    }

    /**
     * 这是一个仅仅是用来测试Dao层的功能是否可以正常进行的测试方法
     */
    public void testDao() {
        //获取数据
        for (int i = 0; i < 20; i++) {
            ArrayList<BackLog> backLogs = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                BackLog backLog = new BackLog(String.valueOf(i), "这是第" + j + "个内容", "2022-01-02", 0);
                backLogs.add(backLog);
            }
            BackLogGroup backLogGroup = new BackLogGroup("这是第" + i + "个组", "2020-11-2", backLogs);
            list.add(backLogGroup);
        }
        dao.insert(list);
        dao.dropTable("back_log_group");
        dao.insert(list);
//        list = dao.queryAll();
    }

    /**
     * 这是一个用来删除测试数据的方法
     */
    public void deleteData() {
        dao.dropTable("back_log_group");
        //删除表是将数据直接清零，但是也会把表销毁，为了保证后续的查询不会失误，这里就需要创建一个空表
        dao.createTable();
    }


    /**
     * 这一段代码只会在程序第一次被安装的时候被执行！
     */
    public synchronized void welcomeData(){
        //获取数据
        List<BackLog> backLogList = new ArrayList<>();
        BackLogGroup backLogGroup = new BackLogGroup("欢迎使用《只要今日了》", TimeUtil.getNowTime(), backLogList);
        ArrayList<BackLogGroup> backLogGroupList = new ArrayList<>();
        backLogGroupList.add(backLogGroup);
        dao.insert(backLogGroupList);
    }

    /**
     * 以下是程序第一次运行的时候会执行的代码块
     */
    public boolean onAppInit(){
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean firstRun = prefs.getBoolean(KEY_FIRST_RUN, true);

        if (firstRun) {
            // 在这里执行您想要在第一次安装应用程序时执行的代码块
            // 第一次启动先初始化(清空)数据库
            deleteData();
//            // 第一次使用软件的时候
            welcomeData();
            // 将SharedPreferences中的值设置为false，表示代码块已经执行过
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean(KEY_FIRST_RUN, false);
            editor.apply();
            return true;
        }
        return false;
    }

}